package com.SmartCampus.system.controller;

import com.SmartCampus.system.annotation.AuthCheck;
import com.SmartCampus.system.common.BaseResponse;
import com.SmartCampus.system.common.DeleteRequest;
import com.SmartCampus.system.common.ErrorCode;
import com.SmartCampus.system.common.ResultUtils;
import com.SmartCampus.system.constant.UserConstant;
import com.SmartCampus.system.exception.BusinessException;
import com.SmartCampus.system.exception.ThrowUtils;
import com.SmartCampus.system.model.dto.activity.ActivityAddRequest;
import com.SmartCampus.system.model.dto.activity.ActivityQueryRequest;
import com.SmartCampus.system.model.dto.activity.ActivityUpdateRequest;
import com.SmartCampus.system.model.entity.Activity;
import com.SmartCampus.system.service.ActivityService;
import com.SmartCampus.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 完满活动接口
 *
 * @author wangliang
 */
@RestController
@RequestMapping("/activity")
@Slf4j
@Api(tags = "完满活动接口")
public class ActivityController {

    @Resource
    private ActivityService activityService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建完满活动（仅管理员）
     *
     * @param activityAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "创建完满活动")
    public BaseResponse<Long> addActivity(@RequestBody ActivityAddRequest activityAddRequest, HttpServletRequest request) {
        if (activityAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = userService.getLoginUser(request).getUsername();
        if (username == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityAddRequest, activity);
        activity.setOrganizer(username);
        boolean result = activityService.save(activity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(activity.getId());
    }

    /**
     * 删除完满活动（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除完满活动")
    public BaseResponse<Boolean> deleteActivity(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能为空");
        }
        boolean result = activityService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新全部的完满活动（仅管理员）
     *
     * @param activityUpdateRequest
     * @return
     */
    @PostMapping("/update/all")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation(value = "更新全部的完满活动（仅管理员）")
    public BaseResponse<Boolean> updateActivityByAll(@RequestBody ActivityUpdateRequest activityUpdateRequest) {
        if (activityUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }

        Activity activity = new Activity();
        BeanUtils.copyProperties(activityUpdateRequest, activity);
        boolean result = activityService.updateById(activity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 更新全部的完满活动（仅组织者）
     *
     * @param activityUpdateRequest
     * @return
     */
    @PostMapping("/update/my")
    @ApiOperation(value = "更新自己的完满活动（仅组织者）")
    public BaseResponse<Boolean> updateActivityByMy(@RequestBody ActivityUpdateRequest activityUpdateRequest, HttpServletRequest request) {
        if (activityUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id 不能小于等于0");
        }
        String username = userService.getLoginUser(request).getUsername();
        if (username == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", activityUpdateRequest.getId());
        if (activityService.count(queryWrapper) == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "活动不存在");
        }
        Activity oldActivity = activityService.getOne(queryWrapper);
        if (!activityUpdateRequest.getOrganizer().equals(oldActivity.getOrganizer())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "只能更新自己的活动");
        }
        if (activityUpdateRequest.getOrganizer() == null || activityUpdateRequest.getOrganizer().equals("")) {
            activityUpdateRequest.setOrganizer(oldActivity.getOrganizer());
        }
        if (activityUpdateRequest.getActivityName() == null || activityUpdateRequest.getActivityName().equals("")) {
            activityUpdateRequest.setActivityName(oldActivity.getActivityName());
        }
        if (activityUpdateRequest.getStartTime() == null || activityUpdateRequest.getStartTime().equals("")) {
            activityUpdateRequest.setStartTime(oldActivity.getStartTime());
        }
        if (activityUpdateRequest.getEndTime() == null || activityUpdateRequest.getEndTime().equals("")) {
            activityUpdateRequest.setEndTime(oldActivity.getEndTime());
        }
        if (activityUpdateRequest.getLocation() == null || activityUpdateRequest.getLocation().equals("")) {
            activityUpdateRequest.setLocation(oldActivity.getLocation());
        }
        if (activityUpdateRequest.getDescription() == null || activityUpdateRequest.getDescription().equals("")) {
            activityUpdateRequest.setDescription(oldActivity.getDescription());
        }
        BeanUtils.copyProperties(activityUpdateRequest, oldActivity);
        boolean result = activityService.updateById(oldActivity);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取全部的完满活动列表
     *
     * @param activityQueryRequest
     * @return
     */
    @PostMapping("/get/all")
    @ApiOperation(value = "分页获取全部的完满活动列表")
    public BaseResponse<Page<Activity>> getActivityByAll(@RequestBody ActivityQueryRequest activityQueryRequest) {
        long current = activityQueryRequest.getCurrent() == 0 ? 1 : activityQueryRequest.getCurrent();
        long size = activityQueryRequest.getPageSize() == 0 ? 10 : activityQueryRequest.getPageSize();
        Page<Activity> page = new Page<>(current, size);
        Page<Activity> activityPage = activityService.getActivityByAll(page, activityQueryRequest);
        if (activityPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(activityPage);
    }

    /**
     * 分页获取组织者组织的完满活动列表
     *
     * @param activityQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/get/my")
    @ApiOperation(value = "分页获取组织者组织的完满活动列表")
    public BaseResponse<Page<Activity>> getActivityByMy(@RequestBody ActivityQueryRequest activityQueryRequest, HttpServletRequest request) {
        if (activityQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String username = userService.getLoginUser(request).getUsername();
        long current = activityQueryRequest.getCurrent() == 0 ? 1 : activityQueryRequest.getCurrent();
        long size = activityQueryRequest.getPageSize() == 0 ? 10 : activityQueryRequest.getPageSize();

        Page<Activity> page = new Page<>(current, size);
        Page<Activity> activityPage = activityService.getActivityByMy(page, activityQueryRequest, username);
        if (activityPage == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询失败，请联系管理员");
        }
        return ResultUtils.success(activityPage);
    }

    // endregion
}
